package com.myapp.web.struts2.multipart;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.ServerContext;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.impl.DaemonThreadFactory;

import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

public class DWRProgressHelper implements Runnable{

	private static final Logger logger = LoggerFactory.getLogger(DWRProgressHelper.class);
			
	private static final ScriptSessionFilter uploadSessionFilter = createScriptSessionFilter();
	
	public DWRProgressHelper(){
		 ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new DaemonThreadFactory());
		 executor.scheduleAtFixedRate(this, 1L, 1L, TimeUnit.SECONDS);
	}
	
	public void updateProgress(){		
		ServerContext context = ServerContextFactory.get();
		if(context == null){
			logger.warn("dwr get the current servercontex ,but it's null.");
			return ;
		}
		String page = context.getContextPath() + "/adm/prod/prodDetail.jsp";
	    Browser.withPageFiltered(page, uploadSessionFilter, new Runnable(){
	        public void run(){	        	
	        	FileUploadListener listener = null;
	            HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
	            //can't use ServletActionContext.getRequest() to get the HttpServletRequest.
	            if (request.getSession().getAttribute(ProgressMultiPartRequest.PROGRESS_KEY) != null){       
	            	listener = (FileUploadListener)request.getSession().getAttribute(ProgressMultiPartRequest.PROGRESS_KEY);
	            }       
	    		if(listener == null){
	    			listener = new FileUploadListener(request.getSession().getId());
	    			request.getSession().setAttribute(ProgressMultiPartRequest.PROGRESS_KEY,listener);
	    			logger.info("get the progress listener from HttpServletRequest,and it not exists.");
	    		}else{
	    			logger.info("get the progress listener from HttpServletRequest,and it exists.");
	    		}
	    		/*for(FileItemProgressInfo fpi : listener.GetProgessInfo())
	    		{
	    			Util.addRows("progress",new String[][]{{
	    				     Integer.valueOf((fpi.getFileIndex())).toString(),
	    					 Long.valueOf(fpi.getBytesRead()).toString(),
	    					 Long.valueOf(fpi.getTotalSize()).toString()
	    		      }});
	    		}*/
	    		
	    		//ScriptSessions.addFunctionCall(
	        } 
	   } );
	}
	
	protected static ScriptSessionFilter createScriptSessionFilter(){ 
		return new ScriptSessionFilter(){
		    public boolean match(ScriptSession session){
		    	String sessionId1  = (String)session.getId();    	
		    	String sessionId2  = (String)WebContextFactory.get().getScriptSession().getId();
		    	if(sessionId1 != null && sessionId1.equalsIgnoreCase(sessionId2)){
		    		return Boolean.TRUE;
		    	}
		    	return Boolean.FALSE;
		    }
		};
	}

	@Override
	public void run() {
		updateProgress();		
	}
}
